package itsmap.systematic.exam;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class PatientInformationActivity extends ListActivity {


	private JSONArray jsonArrayAnswers;
	private JSONObject jsonTestType;
	private ArrayList<JSONObject> jsonArrayObj;
	private testInformationAdapter tia;
	private ListView mInformationListView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.patient_test_information_listview);
		jsonArrayObj = new ArrayList<JSONObject>();
		
		
		mInformationListView = getListView();
		String jsonString = getIntent().getStringExtra("jsonData");
		setContentOfPatientTestList(jsonString, getIntent().getStringExtra("cpr"));
		
		tia = new testInformationAdapter(PatientInformationActivity.this, R.layout.patient_test_information_rowdate, jsonArrayObj);
		mInformationListView.setAdapter(tia);
		
	}
	
	// update list
	private void setContentOfPatientTestList(final String jsonString, String cpr){
		try {
			JSONObject jo = new JSONObject(jsonString);
			
			
			// return an array of dates
			jsonArrayAnswers = jo.getJSONArray("answers");
			
			JSONArray jsondate;
			
			// return an array of values;
			JSONObject temp = jsonArrayAnswers.getJSONObject(3);
			jsondate = temp.getJSONArray("analyses");
			
			int j = 0;
			JSONObject header = new JSONObject();
			header.put("cpr", cpr);
			header.put("date0", jsonArrayAnswers.getJSONObject(j).getString("samplingTime"));
			JSONArray ta0 = jsonArrayAnswers.getJSONObject(j++).getJSONArray("analyses");
			header.put("date1", jsonArrayAnswers.getJSONObject(j).getString("samplingTime"));
			JSONArray ta1 = jsonArrayAnswers.getJSONObject(j++).getJSONArray("analyses");
			header.put("date2", jsonArrayAnswers.getJSONObject(j).getString("samplingTime"));
			JSONArray ta2 = jsonArrayAnswers.getJSONObject(j++).getJSONArray("analyses");
			header.put("date3", jsonArrayAnswers.getJSONObject(j).getString("samplingTime"));
			JSONArray ta3 = jsonArrayAnswers.getJSONObject(j++).getJSONArray("analyses");
			
			JSONArray ja = new JSONArray();
			JSONObject container = new JSONObject();
			String note = "";
			for(int i = 0; i < ta0.length(); i++) {
				container = new JSONObject();
				container.put("analysisName", ta0.getJSONObject(i).getString("analysisName"));								
				container.put("val0", ta0.getJSONObject(i).getString("value"));
				container.put("val0out", ta0.getJSONObject(i).optBoolean("outsideNormalRange", false));
				note = ta0.getJSONObject(i).optString("messageFromLab");
				if(!note.isEmpty()) {
					container.put("val0note", note);
				}
				container.put("val1", "");
				container.put("val2", "");
				container.put("val3", "");
				ja.put(container);
			}
			
			for(int i = 0; i < ta1.length(); i++) {
				String testString = ta1.getJSONObject(i).getString("analysisName");
				boolean found = false;
				for(int k = 0; k < ja.length(); k++) {					
					if(ja.getJSONObject(k).getString("analysisName").equals(testString)) {
						ja.getJSONObject(k).put("val1", ta1.getJSONObject(i).getString("value"));
						ja.getJSONObject(k).put("val1out", ta1.getJSONObject(i).optBoolean("outsideNormalRange", false));
						if(!(note = ta1.getJSONObject(i).optString("messageFromLab")).isEmpty()) {
							ja.getJSONObject(k).put("val1note", note);
						}						
						found = true;
					}
					if(found)
						break;
				}			
				if(!found) {
					container = new JSONObject();
					container.put("analysisName", ta1.getJSONObject(i).getString("analysisName"));
					container.put("val1", ta1.getJSONObject(i).getString("value"));
					container.put("val1out", ta1.getJSONObject(i).optBoolean("outsideNormalRange", false));
					note = ta1.getJSONObject(i).optString("messageFromLab");
					if(!note.isEmpty()) {
						container.put("val1note", note);
					}
					container.put("val0", "");
					container.put("val2", "");
					container.put("val3", "");
					ja.put(container);
				}				
			}
			
			for(int i = 0; i < ta2.length(); i++) {
				String testString = ta2.getJSONObject(i).getString("analysisName");
				boolean found = false;
				for(int k = 0; k < ja.length(); k++) {					
					if(ja.getJSONObject(k).getString("analysisName").equals(testString)) {
						ja.getJSONObject(k).put("val2", ta2.getJSONObject(i).getString("value"));
						ja.getJSONObject(k).put("val2out", ta2.getJSONObject(i).optBoolean("outsideNormalRange", false));
						if(!(note = ta2.getJSONObject(i).optString("messageFromLab")).isEmpty()) {
							ja.getJSONObject(k).put("val2note", note);
						}						
						found = true;
					}
					if(found)
						break;
				}			
				if(!found) {
					container = new JSONObject();
					container.put("analysisName", ta2.getJSONObject(i).getString("analysisName"));
					container.put("val2", ta2.getJSONObject(i).getString("value"));
					container.put("val2out", ta2.getJSONObject(i).optBoolean("outsideNormalRange", false));
					note = ta2.getJSONObject(i).optString("messageFromLab");
					if(!note.isEmpty()) {
						container.put("val2note", note);
					}
					container.put("val0", "");
					container.put("val1", "");
					container.put("val3", "");
					ja.put(container);
				}				
			}
			
			for(int i = 0; i < ta3.length(); i++) {
				String testString = ta3.getJSONObject(i).getString("analysisName");
				boolean found = false;
				for(int k = 0; k < ja.length(); k++) {					
					if(ja.getJSONObject(k).getString("analysisName").equals(testString)) {
						ja.getJSONObject(k).put("val3", ta3.getJSONObject(i).getString("value"));
						ja.getJSONObject(k).put("val3out", ta3.getJSONObject(i).optBoolean("outsideNormalRange", false));
						if(!(note = ta3.getJSONObject(i).optString("messageFromLab")).isEmpty()) {
							ja.getJSONObject(k).put("val3note", note);
						}
						found = true;
					}
					if(found)
						break;
				}			
				if(!found) {
					container = new JSONObject();
					container.put("analysisName", ta3.getJSONObject(i).getString("analysisName"));
					container.put("val3", ta3.getJSONObject(i).getString("value"));
					container.put("val3out", ta3.getJSONObject(i).optBoolean("outsideNormalRange", false));
					note = ta3.getJSONObject(i).optString("messageFromLab");
					if(!note.isEmpty()) {
						container.put("val3note", note);
					}
					container.put("val0", "");
					container.put("val2", "");
					container.put("val1", "");
					ja.put(container);
				}				
			}
			
			// First line, header
			jsonArrayObj.add(header);
			
			for(int i = 0; i < ja.length(); i++){				
				jsonArrayObj.add(ja.getJSONObject(i)); // Value 1
			}
			
			
			
			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private class testInformationAdapter extends ArrayAdapter<JSONObject>{
		private Context mContext;
		private ArrayList<JSONObject> mJsonArray; 
		
		
		public testInformationAdapter(Context context,
				int textViewResourceId, ArrayList<JSONObject> items) {
			super(context, textViewResourceId, items);
			mContext = context;
			mJsonArray = items;
			
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			View v = convertView;
			
			if(v == null){
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.patient_test_information_rowdate, null);
			}
			
			JSONObject jo = mJsonArray.get(position);
			
			if(jo != null){
				
				String cpr = jo.optString("cpr"); 
				if(cpr.isEmpty()) {
				
					TextView tv = (TextView) v.findViewById(R.id.analysesNameId);
					if(tv != null){
						try {
							tv.setText(jo.getString("analysisName"));
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
					TextView tt = (TextView) v.findViewById(R.id.patientTestResultNewstId);
					if(tt != null){
						try {
							String val = jo.getString("val0");						
							tt.setText(val);
							if(val.length() > 0) {
								if(jo.optBoolean("val0out", false)) {
									tt.setTextColor(Color.RED);
								}
								final String note = jo.optString("val0note");
								if(!note.isEmpty()) {								
									SpannableString uline = new SpannableString(val);
									uline.setSpan(new UnderlineSpan(), 0, val.length(), 0);
									tt.setText(uline);
									tt.setOnClickListener(new OnClickListener() {
										@Override
										public void onClick(View v) {
											// TODO Auto-generated method stub
											AlertDialog.Builder builder = new AlertDialog.Builder(PatientInformationActivity.this);
											builder.setMessage(note)
											       .setCancelable(false)
											       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
											           public void onClick(DialogInterface dialog, int id) {
											                // put your code here
											           }
											       });
											AlertDialog alertDialog = builder.create();
											alertDialog.show();																				
										}
									});
								}
							}						
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					TextView tt1 = (TextView) v.findViewById(R.id.patientTestResultNewst1Id);
					if(tt1 != null){
						try {						
							String val = jo.getString("val1");
							tt1.setText(val);
							if(val.length() > 0) {
								if(jo.optBoolean("val1out", false)) {
									tt1.setTextColor(Color.RED);
								}
								final String note = jo.optString("val1note");
								if(!note.isEmpty()) {								
									SpannableString uline = new SpannableString(val);
									uline.setSpan(new UnderlineSpan(), 0, val.length(), 0);
									tt1.setText(uline);								
									tt1.setOnClickListener(new OnClickListener() {
										@Override
										public void onClick(View v) {
											// TODO Auto-generated method stub
											AlertDialog.Builder builder = new AlertDialog.Builder(PatientInformationActivity.this);
											builder.setMessage(note)
											       .setCancelable(false)
											       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
											           public void onClick(DialogInterface dialog, int id) {
											                // put your code here
											           }
											       });
											AlertDialog alertDialog = builder.create();
											alertDialog.show();																				
										}
									});
								}
							}						
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					TextView tt2 = (TextView) v.findViewById(R.id.patientTestResultNewst2Id);
					if(tt2 != null){
						try {						
							String val = jo.getString("val2");
							tt2.setText(val);
							if(val.length() > 0) {
								if(jo.optBoolean("val2out", false)) {
									tt2.setTextColor(Color.RED);
								}
								final String note = jo.optString("val2note");
								if(!note.isEmpty()) {
									SpannableString uline = new SpannableString(val);
									uline.setSpan(new UnderlineSpan(), 0, val.length(), 0);
									tt2.setText(uline);
									tt2.setOnClickListener(new OnClickListener() {
										@Override
										public void onClick(View v) {
											// TODO Auto-generated method stub
											AlertDialog.Builder builder = new AlertDialog.Builder(PatientInformationActivity.this);
											builder.setMessage(note)
											       .setCancelable(false)
											       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
											           public void onClick(DialogInterface dialog, int id) {
											                // put your code here
											           }
											       });
											AlertDialog alertDialog = builder.create();
											alertDialog.show();																				
										}
									});
								}
							}												
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					TextView tt3 = (TextView) v.findViewById(R.id.patientTestResultNewst3Id);
					if(tt3 != null){
						try {						
							String val = jo.getString("val3");						
							tt3.setText(val);
							if(val.length() > 0) {
								if(jo.optBoolean("val3out", false)) {
									tt3.setTextColor(Color.RED);
								}
								final String note = jo.optString("val3note");
								if(!note.isEmpty()) {
									SpannableString uline = new SpannableString(val);
									uline.setSpan(new UnderlineSpan(), 0, val.length(), 0);
									tt3.setText(uline);
									tt3.setOnClickListener(new OnClickListener() {
										@Override
										public void onClick(View v) {
											// TODO Auto-generated method stub
											AlertDialog.Builder builder = new AlertDialog.Builder(PatientInformationActivity.this);
											builder.setMessage(note)
											       .setCancelable(false)
											       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
											           public void onClick(DialogInterface dialog, int id) {
											                // put your code here
											           }
											       });
											AlertDialog alertDialog = builder.create();
											alertDialog.show();																				
										}
									});
								}
							}
							
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} 
					
				} else {
					TextView tv = (TextView) v.findViewById(R.id.analysesNameId);
					TextView tt = (TextView) v.findViewById(R.id.patientTestResultNewstId);
					TextView tt1 = (TextView) v.findViewById(R.id.patientTestResultNewst1Id);
					TextView tt2 = (TextView) v.findViewById(R.id.patientTestResultNewst2Id);
					TextView tt3 = (TextView) v.findViewById(R.id.patientTestResultNewst3Id);
					
					tv.setText("Result information for patient " + 
							cpr.substring(0, 7) + "-" + cpr.substring(6, 10));
					tv.setTextColor(Color.GRAY);
					tt.setText(jo.optString("date0").substring(0, 6));
					tt.setTextColor(Color.GRAY);
					tt1.setText(jo.optString("date1").substring(0, 6));
					tt1.setTextColor(Color.GRAY);
					tt2.setText(jo.optString("date2").substring(0, 6));
					tt2.setTextColor(Color.GRAY);
					tt3.setText(jo.optString("date3").substring(0, 6));
					tt3.setTextColor(Color.GRAY);
				}
			}			
			
			return v;
		}
		
	}
}
